package com.mysecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysecurity.pojo.CrmUser;
import com.mysecurity.pojo.Right;
import com.mysecurity.pojo.SecurityUser;
import com.mysecurity.service.RightService;
import com.mysecurity.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jane
 * @date 2024-06-28 16:25
 */
@Component
public class DBUserDetailsService  implements UserDetailsService {
    @Resource
    UserService userService;

    @Resource
    RightService rightService ;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //认证  && 授权
        QueryWrapper<CrmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("usr_name",username);

        CrmUser crmUser = userService.getOne(queryWrapper);
        if (null== crmUser){
            throw  new UsernameNotFoundException("用户名不存在");
        }

     /*   UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("zhangsan")
                        .password("123456")
                        .roles("USER")
                        .build();*/
        List<Right> rightList = rightService.getPermissionsByRoleId(4);
        List<String> stringList = rightList.stream().map(Right::getRightCode).collect(Collectors.toList());


        return new SecurityUser(crmUser,stringList);//new InMemoryUserDetailsManager(user);
       /* return  new SecurityUser(crmUser
                                , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_sys"));
*/
    }
}
